<template>
  <div class="view-container">
    <el-form :model="queryParam" label-width="auto">
      <el-row :gutter="10">
        <el-col :span="6">
          <el-form-item label="用户凭证" prop="token">
            <el-input v-model="queryParam.token" placeholder="用户token(模糊查询)"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item>
            <el-button type="primary" @click="handleQuery">搜索</el-button>
            <el-button @click="resetParams">重置</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <nebula-table :columns="columns" :data="tableData" border show-overflow-tooltip :total="rowsTotal" header-row-class-name="header-row-class" @change="changePage">
      <template #operation="scope">
        <el-button type="primary" size="small" @click="forceOffline(scope.row)">强制下线</el-button>
      </template>
    </nebula-table>
  </div>
</template>

<script setup>
import {getOnlineUser, offline} from "@/api/onlineUser.js";
import {ElNotification} from "element-plus";
import NebulaTable from "@/components/NebulaTable.vue";

defineOptions({
  name: 'onlineUser'
})

const queryParam = ref({
  token: null,
  pageSize: 10,
  pageNum: 1
})
const rowsTotal = ref(0)
const tableData = ref([])

const page = reactive({
  current: queryParam.value.pageNum,
  limit: queryParam.value.pageSize,
  total: rowsTotal,
  layout: ["prev", "page", "next", "limits", "count"],
});

const columns = [
  {title: "token", key: "token", align: 'center'},
  {title: "用户姓名", key: "nickname", align: 'center'},
  {title: "最近登陆时间", key: "loginTime", align: 'center'},
  {title: "浏览器", key: "browser", align: 'center'},
  {title: "登陆平台", key: "platform", align: 'center'},
  {title: "浏览器引擎", key: "engine", align: 'center'},
  {title: "操作系统", key: "os", align: 'center'},
  {title: "登陆设备数", key: "loginDevices", align: 'center'},
  {title: "IP地址", key: "loginIp", align: 'center'},
  {title: "操作", align: 'center', customSlot: 'operation'}
]

const changePage = (currentPage,pageSize) => {
  queryParam.value.pageNum = currentPage
  queryParam.value.pageSize = pageSize
  handleQuery()
}

const handleQuery = () => {
  getOnlineUser(queryParam.value).then(res => {
    rowsTotal.value = res.data.total
    tableData.value = res.data.rows
  })
}

const resetParams = () => {
  for (let key in queryParam.value) {
    if (key !== "pageNum" && key !== "pageSize") {
      queryParam.value[key] = null;
    }
  }
}

const forceOffline = (row) => {
  offline(row.loginId).then(res => {
    if (res.code === 200) {
      handleQuery()
      ElNotification({
        title: "操作成功",
        type: "success",
      })
    }
  })
}

onMounted(() => {
  handleQuery()
})

</script>
